﻿using AutoMapper;
using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class AddRoleCommandHander : IRequestHandler<AddRoleCommand, ApiResult<object>>
    {
        private readonly IRepistory<Role> _roleRepository;
        private readonly IMapper mapper;

        public AddRoleCommandHander(IRepistory<Role> roleRepository, IMapper mapper)
        {
            _roleRepository = roleRepository;
            this.mapper = mapper;
        }
        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<object>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> apiResult = new ApiResult<object>();
            var rolename = _roleRepository.GetAll().Where(x => x.RoleName == request.RoleName);
            if (rolename.Count() > 0)
            {
                apiResult.code = Renum.添加失败;
                apiResult.Message = "角色名称已存在";
                return Task.FromResult(apiResult);
            }
            var role = mapper.Map<Role>(request);
            role.CreationDate = DateTime.Now;
            role.Creator = "张三";
            role.Updateor = "";
            role.IsDeleted = false;
            _roleRepository.Add(role);
            apiResult.code = Renum.添加成功;
            apiResult.Message = "角色添加成功".ToString();
            return Task.FromResult(apiResult);
        }
    }
}
